<template>
  <div>
    <el-dialog
      title="分配权限"
      :visible="showDialog"
      width="50%"
      @close="close"
    >
      <!-- 权限点树形列表 -->
      <!-- 'name' 后台返回属性名 -->
      <el-tree
        ref="treePoints"
        :data="pointsList"
        :props="{ label: 'name' }"
        check-strictly
        default-expand-all
        show-checkbox
        node-key="id"
      ></el-tree>

      <span slot="footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="assingPoints">分配权限</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// 权限点列表数据接口
import { getPermissionList } from '@/api/permisson'
// 导入转换属性结构的方法
import { formatTreeData } from '@/utils'
// 获取角色选择过的权限点接口
import { getRoleDetail, assignPerm } from '@/api/setting'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      // 权限点列表数据
      pointsList: [],
      // 角色ID
      roleId: ''
    }
  },
  created () {
    this.getPermissions()
  },
  methods: {
    // 给角色分配权限点
    async assingPoints () {
      await assignPerm({ id: this.roleId, permIds: this.$refs.treePoints.getCheckedKeys() })
      this.$message.success('分配成功')
      this.close()
    },
    // 获取当前角色之前选择过的权限点
    // id 父组件传递的角色ID
    async getRoleSeledPoints (id) {
      const res = await getRoleDetail(id)
      this.roleId = id
      // 回显
      this.$refs.treePoints.setCheckedKeys(res.permIds)
    },
    // 获取权限点数据
    async getPermissions () {
      const res = await getPermissionList()
      this.pointsList = formatTreeData(res)
    },
    close () {
      // 清空上次选中的权限
      this.$refs.treePoints.setCheckedKeys([])
      this.$emit('update:showDialog', false)
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
